package com.qf.controller;

import com.qf.utils.JwtUtils;
import com.qf.vo.ResultVo;
import com.qf.vo.VoteVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/vote")
public class VoteController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/dovote")
    public ResultVo dovote(String name, HttpServletRequest request) {

        //1. 谁投的？
        String token = request.getHeader("token");
        String phone = JwtUtils.getUserName(token);

        // 判断手机号是否已经在黑名单中了，如果在直接返回错误
        String blackList = "vote:redcard";
        Boolean flag = redisTemplate.opsForSet()
                .isMember(blackList, phone);
        if (flag){
            // 在黑名单中
            return new ResultVo(-1,"error","你涉嫌刷票，手机号被封，请联系管理员解封");
        }

        // 判断该手机号是否在1分钟之内透过票 ，如果投过就不让继续投票拉
        String voteHistoryKey = "vote:history:"+phone;
        Object o = redisTemplate.opsForValue()
                .get(voteHistoryKey);
        if (o!=null){
            // 1分钟之内，投过票了
            // 记录违规投票次数
            String wgKey = "vote:yellowcard";
            Long wgCount = redisTemplate.opsForHash()
                    .increment(wgKey, phone, 1);
            if (wgCount>2){
                // 加入黑名单，并且返回错误

                redisTemplate.opsForSet()
                        .add(blackList,phone);

                return new ResultVo(-1,"error","你涉嫌刷票，手机号被封，请联系管理员解封");
            }else {
                return new ResultVo(-1,"error","请不要在1分钟内多次投票！！");
            }

        }

        //2. 累加候选人的投票数量
        String key = "vote:info";
        redisTemplate.opsForHash()
                .increment(key,name,1);

        //3. 记录当前投票人的投票流水信息
        String key2 = "vote:"+phone;
        redisTemplate.opsForList()
                .rightPush(key2,new VoteVo(new Date(),name,phone));

        //4. 记录当前手机号已经投过票了，到redis的一个超时时间为1min的key中

        redisTemplate.opsForValue()
                .set(voteHistoryKey,new Date(),1, TimeUnit.MINUTES);

        return new ResultVo(1,"ok",null);
    }

}
